package com.vending.service.impl;

import com.vending.common.exception.BusinessException;
import com.vending.common.utils.JwtUtil;
import com.vending.mapper.UserMapper;
import com.vending.model.dto.LoginRequest;
import com.vending.model.dto.LoginResponse;
import com.vending.model.entity.User;
import com.vending.security.JwtTokenProvider;
import com.vending.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Override
    public LoginResponse login(LoginRequest request) {
        log.info("开始登录，用户名: {}", request.getUsername());
        
        // 查询用户
        User user = userMapper.selectByUsername(request.getUsername());
        if (user == null) {
            log.error("用户不存在");
            throw new BusinessException("用户名或密码错误");
        }
        
        log.info("查询到用户信息: {}", user);
        
        // 验证密码
        log.info("开始验证密码");
        String rawPassword = request.getPassword();
        String storedPassword = user.getPassword().replace("{{ ", "").replace(" }}", "");
        
        boolean matches = passwordEncoder.matches(rawPassword, storedPassword);
        log.info("密码验证结果: {}", matches);
        
        if (!matches) {
            log.error("密码不匹配");
            throw new BusinessException("用户名或密码错误");
        }

        // 检查用户状态
        if (!"ENABLED".equals(user.getStatus())) {
            log.error("用户状态异常: {}", user.getStatus());
            throw new BusinessException("账号已被禁用");
        }

        // 生成token
        String token = jwtTokenProvider.generateToken(user);

        // 构建响应
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setUsername(user.getUsername());
        response.setName(user.getName());
        response.setRole(user.getRole());
        response.setPhone(user.getPhone());
        response.setId(user.getId());

        return response;
    }

    @Override
    public User register(User user) {
        // 检查用户名是否已存在
        User existingUser = userMapper.selectByUsername(user.getUsername());
        if (existingUser != null) {
            throw new BusinessException("用户名已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 设置默认角色
        if (user.getRole() == null) {
            user.setRole("CONSUMER");
        }

        // 保存用户
        userMapper.insert(user);
        return user;
    }
} 